/************************************* * File: references.cpp * Author: Katherine Gibson * Date: 2/11/2016 * Section: N/A * E-mail: k38@umbc.edu * Description: * This program contains example code * for passing by value, by address, * passing a reference *************************************/ using namespace std; #include #define VAL 2 /* prototypes */ void changeOne (int x); /* pass by value */ void changeTwo (int *x); /* pass by address */ void changeThree(int &x); /* pass a reference */ int main() { int x = 4; int *xPtr = &x; /* WE CAN'T DO THIS!!! references must be initialized at declaration*/ // int &xRef; int &xRef = x; /* notice how we didn't assign it to the address of x */ // print a message to the student cout << endl << "******************************************************" << endl << "* The code for this program is well commented, and *" << endl << "* provides explanations for what is occuring and why *" << endl << "******************************************************" << endl << endl; cout << "At this time, the value of x is " << x << endl; cout << endl << "\t PASSING BY VALUE THREE TIMES!"; changeOne(x); /* we can pass by value directly */ changeOne(*xPtr); /* or by dereferencing a pointer */ changeOne(xRef); /* references are just another name for a variable */ cout << endl << "At this time, the value of x is " << x << endl; cout << endl << "\t PASSING BY ADDRESS THREE TIMES!"; changeTwo(&x); /* we can pass an address by passing the address of x */ changeTwo(xPtr); /* or by passing a pointer, whose value is an address */ changeTwo(&xRef); /* we can also pass the address of a reference */ cout << endl << "At this time, the value of x is " << x << endl; cout << endl << "\t PASSING A REFERENCE THREE TIMES!"; /* notice that there is no & or * -- this is handy, but can be confusing, because it may not be clear that we are passing by reference with looking at the prototype */ changeThree(xRef); /* we can pass a reference simply by doing so */ changeThree(x); /* passing a "normal" variable will also work */ changeThree(*xPtr); /* we can also pass a dereferenced pointer */ cout << endl << "At this time, the value of x is " << x << endl << endl; return 0; } /* definitions */ void changeOne (int y) /* pass by value */ { y *= VAL; } void changeTwo (int *yPtr) /* pass by address */ { (*yPtr) *= VAL; } void changeThree(int &yRef) /* pass a reference */ { /* notice that this definition is identical to the one for pass by value, aka the changeOne() function */ yRef *= VAL; }